package site.xuxingcan;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import static site.xuxingcan.Main.MESSAGE_PORT;

public class ServerUtil {
    private ServerSocket serverSocket = null;
    private ArrayList<SocketHelper> socketHelperArrayList = new ArrayList<SocketHelper>();
    private int index = 0;
    private static volatile ServerUtil instance;

    public static ServerUtil getInstance() {
        if (instance == null) {
            synchronized (ServerUtil.class) {
                if (instance == null) {
                    instance = new ServerUtil();
                }
            }
        }
        return instance;
    }

    private ServerUtil() {
        start();
    }

    private void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(MESSAGE_PORT);
                    while (true) {
                        Socket socket = serverSocket.accept();
                        socket.setKeepAlive(true);
                        socket.setSoTimeout(0);
                        SocketHelper socketHelper = new SocketHelper(socket);
                        socketHelperArrayList.add(socketHelper);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public boolean isSend2PhoneSuccess(String string) {
        synchronized (this) {
            if (socketHelperArrayList.size() == 0) {
                return false;
            }
            if (index >= socketHelperArrayList.size()) {
                index = 0;
            }
            SocketHelper socketHelper = socketHelperArrayList.get(index);
            try {
                socketHelper.writeLineAndFlush(string);
                System.out.println("socketHelperArrayList.size() = " + socketHelperArrayList.size());
                System.out.println("index = " + index);
                index++;
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                socketHelperArrayList.remove(socketHelper);
                socketHelper.close();
                return false;
            }
        }
    }

    public Boolean isServerClose(Socket socket) {
        if (socket == null) {
            return true;
        }
        try {
            socket.sendUrgentData(0);//发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
            return false;
        } catch (Exception se) {
            return true;
        }
    }

    public void stop() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
